//
//  DR_HomeVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_HomeVC: DR_BaseVC {

    private let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        return scrollView
    }()
    private let contentView = UIView()
    private let functionView = DR_HomeHeaderView()
    private let filesCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 15, right: 15)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        cv.isScrollEnabled = false // 禁用滚动
        cv.register(DR_HomeFileCell.self, forCellWithReuseIdentifier: DR_HomeFileCell.identifier)
        return cv
    }()
    
    private var allFiles: [DR_FileModel] = []
    private var collectionViewHeightConstraint: Constraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        // 监听文件导入通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleFileImported),
            name: NSNotification.Name("FileImported"),
            object: nil
        )
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 每次显示时刷新文件列表
        loadPDFFiles()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func handleFileImported() {
        // 刷新文件列表
        loadPDFFiles()
    }
    
    private func setupUI() {

        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(functionView)
        contentView.addSubview(filesCollectionView)
        
        // 设置图片选择回调
        functionView.onImagesSelected = { [weak self] images in
            self?.handleImagesSelected(images)
        }
        functionView.functionBlock = { [weak self] idx in
            let selVC = DR_SelectVC()
            selVC.modalPresentationStyle = .fullScreen
            selVC.type = idx
            self?.pushHidingTabBar(selVC, animated: true)
        }
        functionView.selBlock = { [weak self] in
            self?.pushHidingTabBar(DR_SelectOpVC(), animated: true)
        }
        
        // 设置 collection view
        filesCollectionView.delegate = self
        filesCollectionView.dataSource = self

        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.bottom.equalTo(view.safeAreaLayoutGuide)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        functionView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(430)
        }
        
        filesCollectionView.snp.makeConstraints { make in
            make.top.equalTo(functionView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            collectionViewHeightConstraint = make.height.equalTo(0).constraint
            make.bottom.equalToSuperview()
        }
    }
    
    // MARK: - 加载所有文件列表
    private func loadPDFFiles() {
        allFiles = DR_FileManager.shared.getAllFiles()
        filesCollectionView.reloadData()
        
        // 计算并更新 collectionView 高度
        updateCollectionViewHeight()
    }
    
    // MARK: - 更新 CollectionView 高度
    private func updateCollectionViewHeight() {
        guard allFiles.count > 0 else {
            collectionViewHeightConstraint?.update(offset: 0)
            return
        }
        
        // 计算参数
        let columns: CGFloat = 3
        let cellHeight: CGFloat = 210
        let lineSpacing: CGFloat = 16
        let topInset: CGFloat = 0
        let bottomInset: CGFloat = 15
        
        // 计算行数
        let rowCount = ceil(CGFloat(allFiles.count) / columns)
        
        // 计算总高度：顶部边距 + 行数 * cell高度 + (行数-1) * 行间距 + 底部边距
        let totalHeight = topInset + rowCount * cellHeight + (rowCount - 1) * lineSpacing + bottomInset
        
        // 更新约束
        collectionViewHeightConstraint?.update(offset: totalHeight)
//        filesCollectionView.snp.updateConstraints { make in
//            make.height.equalTo(totalHeight)
//        }
        
        // 更新 contentView 的底部约束，确保 scrollView 可以滚动
        view.layoutIfNeeded()
    }
    
    // MARK: - 显示更多选项弹窗
    private func showMoreActionSheet(for fileModel: DR_FileModel) {
        let actionSheet = DR_FileMoreActionSheet()
        
        // 将 DR_FileModel 转换为 DR_SearchFileModel
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateString = dateFormatter.string(from: fileModel.createDate)
        
        let searchFileModel = DR_SearchFileModel(
            fileName: fileModel.displayName,
            date: dateString,
            size: fileModel.fileSizeString,
            isFavorite: DR_FileManager.shared.isFavorite(fileModel),
            fileType: fileModel.fileType.rawValue
        )
        
        // 根据文件类型决定显示哪些操作
        var actions: [DR_FileMoreAction] = []
        
        // PDF 特有操作
        if fileModel.fileType == .pdf {
            actions.append(DR_FileMoreAction(title: "home_merge".localized, iconName: "more_merge", action: { [weak self] in
                self?.handleMergePDF()
            }))
            actions.append(DR_FileMoreAction(title: "home_split".localized, iconName: "more_split", action: { [weak self] in
                self?.handleSplitPDF(fileModel)
            }))
            
            // 根据是否已设置密码显示不同的操作
            let lockTitle = DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) ? "Unlock PDF" : "home_lock".localized
            actions.append(DR_FileMoreAction(title: lockTitle, iconName: "more_lock", action: { [weak self] in
                self?.handleLockPDF(fileModel)
            }))
        }
        
        // 通用操作
        actions.append(DR_FileMoreAction(title: "more_rename".localized, iconName: "more_rename", shouldAutoHide: false, action: { [weak self, unowned actionSheet] in
            // 手动隐藏 actionSheet，然后显示重命名弹窗
            actionSheet.hide()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self?.handleRenameFile(fileModel)
            }
        }))
        // 根据收藏状态设置不同的标题和图标
        let isFavorite = DR_FileManager.shared.isFavorite(fileModel)
        let favoriteTitle = isFavorite ? "more_collected".localized : "more_collection".localized
        let favoriteIcon = isFavorite ? "home_collected" : "home_collect"
        actions.append(DR_FileMoreAction(title: favoriteTitle, iconName: favoriteIcon, action: { [weak self] in
            self?.handleToggleFavorite(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_share".localized, iconName: "more_share", action: { [weak self] in
            self?.handleShareFile(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_details".localized, iconName: "more_detail", action: { [weak self] in
            self?.handleShowDetails(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_delete".localized, iconName: "more_del", action: { [weak self] in
            self?.handleDeleteFile(fileModel)
        }))
        
        actionSheet.configure(with: searchFileModel, actions: actions)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindow {
            actionSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            actionSheet.show(in: tabBarController.view)
        } else {
            actionSheet.show(in: view)
        }
    }
    
    // MARK: - 处理重命名
    private func handleRenameFile(_ fileModel: DR_FileModel) {
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: fileModel.displayName)
        
        renameSheet.onConfirm = { [weak self] newName in
            guard let self = self else { return }
            
            // 根据文件类型调用不同的重命名方法
            if fileModel.fileType == .pdf {
                if let _ = DR_PDFTool.shared.renamePDF(oldFileURL: fileModel.fileURL, newName: newName) {
                    self.loadPDFFiles()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            } else {
                // 其他文件类型的重命名
                if let _ = self.renameFile(oldFileURL: fileModel.fileURL, newName: newName) {
                    self.loadPDFFiles()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            }
        }
        
        renameSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindow {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    // MARK: - 重命名文件（通用）
    private func renameFile(oldFileURL: URL, newName: String) -> URL? {
        let fileExtension = oldFileURL.pathExtension
        let sanitizedName = sanitizeFileName(newName)
        let newURL = oldFileURL.deletingLastPathComponent().appendingPathComponent("\(sanitizedName).\(fileExtension)")
        
        // 检查新文件名是否已存在
        if FileManager.default.fileExists(atPath: newURL.path) {
            return nil
        }
        
        // 重命名文件
        do {
            try FileManager.default.moveItem(at: oldFileURL, to: newURL)
            return newURL
        } catch {
            print("❌ [DR_HomeVC] 文件重命名失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    // MARK: - 清理文件名
    private func sanitizeFileName(_ fileName: String) -> String {
        let invalidChars = CharacterSet(charactersIn: "/\\?%*|\"<>")
        return fileName.components(separatedBy: invalidChars).joined(separator: "_")
    }
    
    // MARK: - 处理Merge PDF
    private func handleMergePDF() {
        let selVC = DR_SelectVC()
        selVC.type = 1
        pushHidingTabBar(selVC, animated: true)
    }
    
    // MARK: - 处理Split PDF
    private func handleSplitPDF(_ fileModel: DR_FileModel) {
        // 检查PDF是否被锁定
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // PDF已锁定，需要先输入密码
            let passwordSheet = DR_EnterPasswordSheet()
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    sheet.hide()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        self.openSplitPDFVC(fileModel.fileURL)
                    }
                } else {
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {}
            
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // PDF未锁定，直接打开Split页面
            openSplitPDFVC(fileModel.fileURL)
        }
    }
    
    private func openSplitPDFVC(_ fileURL: URL) {
        let splitVC = DR_SplitPDFVC(pdfFileURL: fileURL)
        pushHidingTabBar(splitVC, animated: true)
    }
    
    // MARK: - 处理收藏切换
    private func handleToggleFavorite(_ fileModel: DR_FileModel) {
        let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
        if isNowFavorite {
            view.makeToast("collect_succ".localized, duration: 2.0, position: .center)
        } else {
            view.makeToast("collect_error".localized, duration: 2.0, position: .center)
        }
        loadPDFFiles()
    }
    
    // MARK: - 处理分享
    private func handleShareFile(_ fileModel: DR_FileModel) {
        let activityVC = UIActivityViewController(activityItems: [fileModel.fileURL], applicationActivities: nil)
        
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
    
    // MARK: - 处理显示详情
    private func handleShowDetails(_ fileModel: DR_FileModel) {
        let detailsSheet = DR_FileDetailsSheet()
        detailsSheet.configure(with: fileModel)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindow {
            detailsSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            detailsSheet.show(in: tabBarController.view)
        } else {
            detailsSheet.show(in: view)
        }
    }
    
    // MARK: - 处理锁定/解锁 PDF
    private func handleLockPDF(_ fileModel: DR_FileModel) {
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // 已设置密码，先验证密码再解锁
            let passwordSheet = DR_EnterPasswordSheet()
            
            // 配置文件信息
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                
                // 验证密码
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    // 密码正确，移除密码
                    if DR_PDFTool.shared.removePassword(for: fileModel.fileURL) {
                        sheet.hide()
                        self.view.makeToast("密码已移除", duration: 2.0, position: .center)
                    } else {
                        self.view.makeToast("操作失败", duration: 2.0, position: .center)
                    }
                } else {
                    // 密码错误，显示错误信息（不关闭弹窗）
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindow {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // 未设置密码，显示设置密码弹窗
            let passwordSheet = DR_SetPasswordSheet()
            
            passwordSheet.onConfirm = { [weak self] password in
                guard let self = self else { return }
                if DR_PDFTool.shared.setPassword(for: fileModel.fileURL, password: password) {
                    self.view.makeToast("密码设置成功", duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("密码设置失败", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindow {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        }
    }
    
    // MARK: - 处理删除
    private func handleDeleteFile(_ fileModel: DR_FileModel) {
        let deleteSheet = DR_DeleteConfirmSheet()
        
        deleteSheet.onDelete = { [weak self] in
            guard let self = self else { return }
            do {
                // 删除前先移除收藏
                DR_FileManager.shared.removeFavorite(fileModel)
                try FileManager.default.removeItem(at: fileModel.fileURL)
                self.loadPDFFiles()
                self.view.makeToast("del_succ".localized, duration: 2.0, position: .center)
            } catch {
                self.view.makeToast("del_error".localized, duration: 2.0, position: .center)
            }
        }
        
        deleteSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindow {
            deleteSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            deleteSheet.show(in: tabBarController.view)
        } else {
            deleteSheet.show(in: view)
        }
    }
    
    // MARK: - 处理选中的图片
    private func handleImagesSelected(_ images: [UIImage]) {
        print("选中了 \(images.count) 张图片")
        
        // 显示加载提示
        view.makeToastActivity(.center)
        
        // 在后台线程处理 PDF 生成
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            // 生成 PDF
            guard let pdfModel = DR_PDFTool.shared.createPDF(from: images) else {
                DispatchQueue.main.async {
                    self?.view.hideToastActivity()
                    self?.view.makeToast("pdr_generaF".localized, duration: 2.0, position: .center)
                }
                return
            }
            
            // 回到主线程显示结果并跳转到预览页面
            DispatchQueue.main.async {
                self?.view.hideToastActivity()
                print("✅ PDF 已保存: \(pdfModel.fileURL.path)")
                
                // 刷新文件列表
                self?.loadPDFFiles()
                
                // 跳转到预览页面
                let previewVC = DR_LookPDFVC()
                previewVC.configure(with: pdfModel)
                self?.pushHidingTabBar(previewVC, animated: true)
            }
        }
    }
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_HomeVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_HomeFileCell.identifier, for: indexPath) as! DR_HomeFileCell
        let fileModel = allFiles[indexPath.item]
        let isFavorite = DR_FileManager.shared.isFavorite(fileModel)
        
        cell.configure(with: fileModel, isFavorite: isFavorite)
        
        cell.onFavoriteTapped = { [weak self] in
            guard let self = self else { return }
            let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
            // 刷新当前 cell
            if let cell = collectionView.cellForItem(at: indexPath) as? DR_HomeFileCell {
                cell.configure(with: fileModel, isFavorite: isNowFavorite)
            }
        }
        
        cell.onMoreTapped = { [weak self] in
            self?.showMoreActionSheet(for: fileModel)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        let fileModel = allFiles[indexPath.item]
        
        // PDF 文件使用 DR_LookPDFVC 预览
        if fileModel.fileType == .pdf {
            // 检查PDF是否被锁定
            if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
                // PDF已锁定，需要先输入密码
                showPasswordInputForPDF(fileModel)
            } else {
                // PDF未锁定，直接进入预览
                openPDFPreview(fileModel)
            }
        } else {
            // Word、Excel、PPT 文件使用 DR_LookFileVC 预览
            let previewVC = DR_LookFileVC()
            previewVC.configure(with: fileModel)
            pushHidingTabBar(previewVC, animated: true)
        }
    }
    
    // MARK: - 显示PDF密码输入弹窗
    private func showPasswordInputForPDF(_ fileModel: DR_FileModel) {
        let passwordSheet = DR_EnterPasswordSheet()
        
        // 配置文件信息
        passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            
            // 验证密码
            if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                // 密码正确，关闭弹窗并进入预览
                sheet.hide()
                // 等待弹窗隐藏动画完成后再push
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.openPDFPreview(fileModel, isPasswordVerified: true)
                }
            } else {
                // 密码错误，显示错误信息（不关闭弹窗）
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindow {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    // MARK: - 打开PDF预览
    private func openPDFPreview(_ fileModel: DR_FileModel, isPasswordVerified: Bool = false) {
        let pdfModel = DR_PDFFileModel(
            fileName: fileModel.fileName,
            fileURL: fileModel.fileURL,
            fileSize: fileModel.fileSize,
            createDate: fileModel.createDate,
            pageCount: fileModel.pageCount
        )
        let previewVC = DR_LookPDFVC()
        previewVC.configure(with: pdfModel, isPasswordVerified: isPasswordVerified)
        pushHidingTabBar(previewVC, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let w = (w_screen - 30 - 24)/3
        return CGSize(width: w, height: 210)
    }
}

